package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.domain.JazGroupSpecsDO;
import com.jinzhi.jzweb.domain.vo.*;
import com.jinzhi.jzweb.service.JazGroupSpecsService;
import com.jinzhi.sys.service.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazGroupProdDao;
import com.jinzhi.jzweb.domain.JazGroupProdDO;
import com.jinzhi.jzweb.service.JazGroupProdService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * 团购商品表
 * </pre>
 * <small> 2024-05-11 13:54:18 | Long</small>
 */
@Service
public class JazGroupProdServiceImpl extends CoreServiceImpl<JazGroupProdDao, JazGroupProdDO> implements JazGroupProdService {

    @Autowired
    private JazGroupSpecsService jazGroupSpecsService;
    @Autowired
    private UserRoleService userRoleService;

    public UserDO getUser() {
        return ShiroUtils.getSysUser();
    }

    public Long getUserId() {
        return getUser().getId();
    }
    @Override
    public Result<Page<JazGroupProdDO>> selGroupProdList(String name, int current, int size) {
        Page<JazGroupProdDO> page = new Page<>(current, size);
        Wrapper<JazGroupProdDO> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", "%" + name + "%");
        }
        wrapper.orderBy("-sort",false);
        wrapper.orderBy("create_time",false);
        List<JazGroupProdDO> list = new ArrayList<>();
        Page<JazGroupProdDO> jazGroupProdDOPage = this.selectPage(page, wrapper);
        for (JazGroupProdDO jazGroupProdDo : jazGroupProdDOPage.getRecords()) {
            JazGroupProdDO vo = new JazGroupProdDO();
            BeanUtils.copyProperties(jazGroupProdDo, vo);

            List<JazGroupSpecsVo> voList = new ArrayList<>();
            List<JazGroupSpecsDO> doList = jazGroupSpecsService.selectList(new EntityWrapper<JazGroupSpecsDO>().eq("group_prod_id", jazGroupProdDo.getId()));
            for (JazGroupSpecsDO jazGroupSpecsDO : doList) {
                JazGroupSpecsVo vo1 = new JazGroupSpecsVo();
                BeanUtils.copyProperties(jazGroupSpecsDO, vo1);
                vo1.setGroupPrice(jazGroupSpecsDO.getGroupPrice().doubleValue());
                vo1.setPrice(jazGroupSpecsDO.getPrice().doubleValue());
                vo1.setOriginalPrice(jazGroupSpecsDO.getOriginalPrice().doubleValue());
                voList.add(vo1);
            }
            vo.setVoList(voList);
            list.add(vo);
            jazGroupProdDOPage.setRecords(list);
        }
        return Result.ok(jazGroupProdDOPage);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGroupProd(JazGroupProdVo jazGroupProd) throws ParseException {
        JazGroupProdDO jazGroupProdDO = new JazGroupProdDO();
        BeanUtils.copyProperties(jazGroupProd, jazGroupProdDO);
        jazGroupProdDO.setStartTime(stringToDate(jazGroupProd.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        jazGroupProdDO.setEndTime(stringToDate(jazGroupProd.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        jazGroupProdDO.setProdStatus(0);
        // 获取当前用户的角色
        List<String> roleNames = userRoleService.selroleNameList(ShiroUtils.getUserId());
        // 使用 HashSet 来存储角色名，以便快速查找
        Set<String> roleSet = new HashSet<>(roleNames);
        if(roleSet.contains("超级用户角色")) {
            // 设置状态为已审核
            jazGroupProdDO.setCheckStatus(1);
        }else {
            // 设置状态为待审核
            jazGroupProdDO.setCheckStatus(0);
        }
        jazGroupProdDO.setCheckResult(jazGroupProd.getCheckResult());
        jazGroupProdDO.setCreateTime(new Date());
        jazGroupProdDO.setCreateId(this.getUserId());
//        jazGroupProdDO.setCreateId(1504759468294201346L);

        this.insert(jazGroupProdDO);
        JazGroupSpecsDO jazGroupSpecsDO;
        List<JazGroupSpecsVo> voList = jazGroupProd.getVoList();
        for (JazGroupSpecsVo vo : voList) {
            jazGroupSpecsDO = new JazGroupSpecsDO();
            jazGroupSpecsDO.setGroupProdId(jazGroupProdDO.getId());
            jazGroupSpecsDO.setName(vo.getName());
            jazGroupSpecsDO.setGroupPrice(BigDecimal.valueOf(vo.getGroupPrice()));
            jazGroupSpecsDO.setPrice(BigDecimal.valueOf(vo.getPrice()));
            jazGroupSpecsDO.setOriginalPrice(BigDecimal.valueOf(vo.getOriginalPrice()));
            jazGroupSpecsService.insert(jazGroupSpecsDO);
        }

    }

    @Override
    public JazGroupProdVo getInfo(Long id) {
        JazGroupProdVo vo = new JazGroupProdVo();
        JazGroupProdDO jazGroupProdDO = this.selectById(id);
        List<JazGroupSpecsVo> voList = new ArrayList<>();
        BeanUtils.copyProperties(jazGroupProdDO, vo);
        List<JazGroupSpecsDO> doList = jazGroupSpecsService.selectList(new EntityWrapper<JazGroupSpecsDO>().eq("group_prod_id", id));
        for (JazGroupSpecsDO jazGroupSpecsDO : doList) {
            JazGroupSpecsVo vo1 = new JazGroupSpecsVo();
            BeanUtils.copyProperties(jazGroupSpecsDO, vo1);
            voList.add(vo1);
        }
        vo.setVoList(voList);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupProd(JazGroupProdVo jazGroupProd) throws ParseException {
        JazGroupProdDO jazGroupProdDO = this.selectById(jazGroupProd.getId());
        BeanUtils.copyProperties(jazGroupProd, jazGroupProdDO);
        jazGroupProdDO.setCheckResult(jazGroupProd.getCheckResult());
        jazGroupProdDO.setStartTime(stringToDate(jazGroupProd.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        jazGroupProdDO.setEndTime(stringToDate(jazGroupProd.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        jazGroupProdDO.setUpdateId(this.getUserId().toString());
        jazGroupProdDO.setUpdateTime(new Date());
        this.updateById(jazGroupProdDO);
        List<JazGroupSpecsVo> voList = jazGroupProd.getVoList();
        for (JazGroupSpecsVo vo : voList) {
            JazGroupSpecsDO jazGroupSpecsDO = new JazGroupSpecsDO();
            jazGroupSpecsDO.setGroupProdId(jazGroupProdDO.getId());
            jazGroupSpecsDO.setName(vo.getName());
            jazGroupSpecsDO.setGroupPrice(BigDecimal.valueOf(vo.getGroupPrice()));
            jazGroupSpecsDO.setPrice(BigDecimal.valueOf(vo.getPrice()));
            jazGroupSpecsDO.setOriginalPrice(BigDecimal.valueOf(vo.getOriginalPrice()));

            if (vo.getIsDelete() != null && vo.getId() != null) {
                // 先判断是否需要删除
                jazGroupSpecsService.deleteById(vo.getId());
            } else if (vo.getId() != null) {
                // 然后判断ID是否存在，存在则更新
                jazGroupSpecsDO.setId(vo.getId());
                jazGroupSpecsService.updateById(jazGroupSpecsDO);
            } else {
                // ID不存在，说明是新记录，执行插入
                jazGroupSpecsService.insert(jazGroupSpecsDO);
            }

        }

    }

    /**
     * 将字符串转换为日期对象
     *
     * @param dateString    日期字符串
     * @param formatPattern 日期格式字符串，例如"yyyy-MM-dd HH:mm:ss"
     * @return 转换后的Date对象
     * @throws ParseException 如果日期字符串不能按照给定格式解析，则抛出此异常
     */
    public static Date stringToDate(String dateString, String formatPattern) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatPattern);
        return formatter.parse(dateString);
    }
}
